package com.authine.cloudpivot.ext.service.ipml;

import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.UserFacade;
import com.authine.cloudpivot.engine.api.model.dto.SimpleMsgDTO;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.enums.type.IMMessageChannelType;
import com.authine.cloudpivot.engine.enums.type.IMMessageType;
import com.authine.cloudpivot.engine.service.impl.component.RuntimeMessageComponent;
import com.authine.cloudpivot.engine.service.message.IMessageService;
import com.authine.cloudpivot.ext.service.BlowWhistleEventService;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import com.authine.cloudpivot.util.StringUtil;
import com.authine.cloudpivot.web.api.service.EngineService;
import com.mchange.lang.IntegerUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.Integers;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class BlowWhistleEventServiceIpml implements BlowWhistleEventService {

    //需要推送节点
    private Map<String,Integer> pushActivity;


    private String workCode ="ce_001";


    @Autowired
    private JPANativeQuery jpaNativeQuery;
    @Autowired
    private UserFacade userFacade;


    private BlowWhistleEventServiceIpml(){

        pushActivity = new HashMap();

        //需要推送的节点
         String [] pushActivity01 ={"Activity23","Activity24","Activity25","Activity13","Activity26"};
        for (String key : pushActivity01) {
            pushActivity.put(key,1);
        }

        //需要推送的节点
         String [] pushActivity02 ={"Activity3","Activity5"};
        for (String key : pushActivity02) {
            pushActivity.put(key,120);
        }

        //需要推送的节点
         String [] pushActivity03 ={"Activity8","Activity9"};
        for (String key : pushActivity03) {
            pushActivity.put(key,24);
        }


    }


    @Override
    public void pushTimedOutToDo() {

        //校验是否推送
       if (virifyPush()){
           return;
       }

       String lly ="Activity8,Activity9,Activity13";

        String title="超时提醒";
        String cont="您的【%s】已经超时，请及时处理！";

        LocalDateTime nowTime = LocalDateTime.now(); //先取当前时间
        String activitys = StringUtil._StringTa(pushActivity.keySet());

        String querySql = String.format("select bim.instanceName,bim.participant,bim.instanceId,bim.activityCode,bim.startTime,ce.lly from biz_workitem bim  \n" +
                        "LEFT JOIN ikhmj_chuishao_001 ce on bim.instanceId = ce.workflowInstanceId where bim.workflowCode = '%s' and bim.activityCode in (%s) ;"
                ,workCode,activitys);

        String update ="update ikhmj_chuishao_001 set isTimeOut = '1' where workflowInstanceId ='%s'";


        List list =null;
        try {

             list = jpaNativeQuery.getList(querySql, null, null);
        } catch (Exception e) {
            log.info("超时提醒查询SQL:",querySql);
            log.error("查询异常：",e);
        }
        if (null == list && list.isEmpty()){
            log.info("超时提醒无数据需要推送");
            return;
        }
        //创建推送服务
        IMessageService messageService = RuntimeMessageComponent.getMessageService(IMMessageChannelType.DINGTALK.name());
        DateTimeFormatter form = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (Object res : list) {
            HashMap map = (HashMap) res;
            String activityCode = MapUtils.getString(map, "activityCode");
            Integer integer = pushActivity.get(activityCode);
            if (null == integer && 0  == integer){
                log.debug("当前节点：{} 无审批人，跳过推送",activityCode);
            }
            String time = StringUtil.dateTransition(MapUtils.getString(map, "startTime"),"yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTime = LocalDateTime.parse(time,form);


            if (virifyPush(nowTime,startTime,integer)){
                String instanceName = MapUtils.getString(map, "instanceName");
                String participant = MapUtils.getString(map, "participant");
                String instanceId = MapUtils.getString(map, "instanceId");
                String llyId = MapUtils.getString(map, "lly");
                cont = String.format(cont,instanceName);
                UserModel user = userFacade.get(participant);

                this.senDingTalkMessage(messageService,user,title,cont);
                log.info("【待办超时推送消息】：用户:{}，标题：{}，内容：{}",user.getName() ,title, cont);
                jpaNativeQuery.getList(String.format(update,instanceId),null, null);

                //联络员推送
                if(lly.contains(activityCode)){

                    if (StringUtils.isEmpty(llyId)){

                        log.warn("节点：{}，联络员为空不推送消息");

                    }else {

                        UserModel userLy = userFacade.get(llyId);
                        this.senDingTalkMessage(messageService,userLy,title,cont);
                        log.info("【待办超时推送消息--联络员】：用户:{}，标题：{}，内容：{}",userLy.getName() ,title, cont);

                    }

                }


            }

        }

    }



    /**
     * 验证当前时间是否需要进行推送
     * @return  true=不推送  false = 提送
     * */
    private  boolean virifyPush(){
        int hour = LocalDateTime.now().getHour();

        List list = jpaNativeQuery.getList("select * from push_hour ", null, null);
        HashMap hashMap = (HashMap) list.get(0);
        Integer start = MapUtils.getInteger(hashMap, "start", 0);
        Integer end = MapUtils.getInteger(hashMap, "end", 24);


        if (start <= hour && end >= hour ){
            return false;
        }

        log.warn("当前时间段为：{}时，不进行推送",hour);
        return true;
    }


    /**
     * 验证当前时间是否需要进行推送
     * @return  true=推送  false = 不提送
     * */
    private  boolean virifyPush(LocalDateTime localDateTime,LocalDateTime startTime,Integer integer){

        Duration duration = Duration.between(startTime, localDateTime);
        long minutes = duration.toMinutes();

        long pus = minutes % 60;
        //只有pus 值 在 0 和 10 之间可以推送
        if(integer >pus && 0 <= pus && 10 >= pus){
            return true;
        }

        log.debug("当前时间不在推送时间范围不进行推送， 实际相差：{}分钟",pus);
        return false;
    }



    private void senDingTalkMessage(IMessageService messageService, UserModel user , String title, String content){

        if (StringUtils.isEmpty(user.getUserId())){
            log.warn("用户钉钉ID为空，不推送钉钉消息！");
            return;
        }

        SimpleMsgDTO dto = new SimpleMsgDTO();
        try {

            //钉钉userId
            dto.setReceivers(user.getUserId());
            dto.setContent(content);
            dto.setTitle(title);
            dto.setMessageType(IMMessageType.BUSINESS_REMIND);
            dto.setCorpId(user.getCorpId());
            messageService.sendSimpleTextMsg(dto);
        } catch (Exception e) {
            log.info("用户：{}-账号：{}，送消息内容：{}",user.getName(),user.getUsername(),JSONObject.toJSONString(dto));
            log.error("钉钉消息发送失败",e);
        }
    }

}
